﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.ServiceModel;

namespace Arete
{

    public delegate void MessageEvent(object sender, MessageEventArgs e);

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MyPublisher : IMyContract
    {
        private static MessageEvent msgEvent; 
        static Action m_Event1 = delegate { };
        static Dictionary<string, Action> Subs = 
            new Dictionary<string, Action>();
        
        public void SubscribeEvent()
        {
            var subscriber = OperationContext.Current.GetCallbackChannel<IMyEvents>();
            m_Event1 += subscriber.Event1;
            msgEvent += subscriber.MessageEvent; 
            //Subs.Add();
        }

        public void DoSomethingAndFireEvent()
        {
            var subList = m_Event1.GetInvocationList();
            foreach (Action dlg in subList)
            {
                try { dlg(); }
                catch (Exception X)
                {
                    var removeFromList 
                        = X is SocketException ||
                          X is IOException ||
                          X is RemotingException;
                    if (!removeFromList) continue;
                    m_Event1 -= dlg as Action;
                    throw;
                }
            }
        }

        public void SendMessageAndFireEvent(string message)
        {
            var meList = msgEvent.GetInvocationList();
            foreach (MessageEvent me in meList)
            {
                try { me(null, new MessageEventArgs(message)); }
                catch (Exception X)
                {
                    var removeFromList 
                        = X is SocketException ||
                          X is IOException ||
                          X is RemotingException;
                    if (!removeFromList) continue;
                    msgEvent -= me as MessageEvent;
                    throw;
                }
            }
        }

    }
}